package cn.iocoder.yudao.module.engine.model.context;

import cn.iocoder.yudao.module.engine.dal.redis.engine.EngineCacheRedisDAO;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

@Data
public class EngineTimerStatusCacheContext {
    @JsonIgnore
    private String gameMatchId;
    @JsonIgnore
    private EngineCacheRedisDAO engineCacheRedisDAO;

    // 定时提醒任务触发次数
    private final Map<String, Integer> remindTimerId2TriggerCount = Collections.synchronizedMap(new HashMap<>());

    public EngineTimerStatusCacheContext() {
    }

    public EngineTimerStatusCacheContext(String gameMatchId, EngineCacheRedisDAO engineCacheRedisDAO) {
        this.gameMatchId = gameMatchId;
        this.engineCacheRedisDAO = engineCacheRedisDAO;
    }

    public Integer getTriggerCount(String remindTimerId) {
        synchronized (remindTimerId2TriggerCount) {
            return remindTimerId2TriggerCount.getOrDefault(remindTimerId, 0);
        }
    }

    public EngineTimerStatusCacheContext addTriggerCount(String remindTimerId) {
        synchronized (remindTimerId2TriggerCount) {
            remindTimerId2TriggerCount.put(remindTimerId, getTriggerCount(remindTimerId) + 1);
            return this;
        }
    }

    // 同步到redis
    public void syn() {
        synchronized (remindTimerId2TriggerCount) {
            engineCacheRedisDAO.addEngineTimerStatusCache(gameMatchId, this);
        }
    }
}
